package com.yenlien.traceyun.plant.controller;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.interceptor.CommonProperties;
import com.yenlien.traceyun.common.crypt.CryptUtil;
import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.common.utils.FileUtil;
import com.yenlien.traceyun.common.utils.RandomUtil;
import com.yenlien.traceyun.plant.bean.DevDTO;
import com.yenlien.traceyun.plant.dao.FruitUserDao;
import com.yenlien.traceyun.plant.dao.ShiJiRuiTongDao;
import com.yenlien.traceyun.plant.dock_device.sjrt.*;
import com.yenlien.traceyun.plant.entity.FruitUser;
import com.yenlien.traceyun.plant.entity.ShiJiRuiTong;
import com.yenlien.traceyun.plant.utils.MathUtils;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.exception.BusinessException;
import com.yenlien.traceyun.webase.exception.ErrorPageException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yenlien.traceyun.plant.dock_device.DevState.EQU_TYPE_KILL_INSECT;
import static com.yenlien.traceyun.plant.dock_device.DevState.EQU_TYPE_VIDEO;

/**
 * @Date 2022/12/13
 * @Author jiaLong
 * @Descript 果园小程序
 */
@RestController
@RequestMapping("/fruitApp")
public class FruitAppController extends BaseController {

    @Autowired
    private ShiJiRuiTongDao shiJiRuiTongDao;



    // 首页数据
    @GetMapping(value = "/getDevData")
    public Object getDevData(String type) {
        if (StringUtils.isBlank(type))
            type = "cw";
        List<DevDTO> allDev = new ArrayList<>();
        if("cw".equals(type)){
            GetCWDevData.getToken();
            allDev = GetCWDevData.getAllDev();
        }
        else if("sf".equals(type)){
            GetCWDevDataSF.getToken();
            allDev = GetCWDevDataSF.getAllDev();
            allDev.addAll(FruitController.sfVideoList);
        }
        else if("rj".equals(type)){
            GetCWDevDataRJ.getToken();
            allDev = GetCWDevDataRJ.getAllDev();
            allDev.addAll(FruitController.rjVideoList);
        }
        else if("qfx".equals(type)){
            GetCWDevData.getToken();
            allDev = GetCWDevData.getAllDev().stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
        }
//        if ("cw".equals(type)){
//            if(CollectionUtils.isNotEmpty(GetCWDevData.allDev)){
//                allDev = GetCWDevData.allDev;
//            }else{
//                allDev = GetCWDevData.getAllDev();
//                GetCWDevData.allDev = allDev;
//            }
//        }
//        else if ("sf".equals(type)){
//            if(CollectionUtils.isNotEmpty(GetCWDevDataSF.allDev)){
//                allDev = GetCWDevDataSF.allDev;
//            }else{
//                allDev = GetCWDevDataSF.getAllDev();
//                GetCWDevDataSF.allDev = allDev;
//            }
//        }
//        else if("qfx".equals(type)){
//            if(CollectionUtils.isNotEmpty(GetCWDevData.allDev)){
//                allDev = GetCWDevData.allDev;
//            }else{
//                allDev = GetCWDevData.getAllDev();
//                GetCWDevData.allDev = allDev;
//            }
//            allDev = allDev.stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
//        }
//        else if("rj".equals(type)){
//            if(CollectionUtils.isNotEmpty(GetCWDevDataRJ.allDev)){
//                allDev = GetCWDevDataRJ.allDev;
//            }else{
//                allDev = GetCWDevDataRJ.getAllDev();
//                GetCWDevDataRJ.allDev = allDev;
//            }
//        }

        Long onlineNum = 0L;
        Long offlineNum = 0L;
        JSONObject object = new JSONObject();
        LocalDateTime now = LocalDateTime.now();
        for(DevDTO devDTO : allDev){

            if("qfx".equals(type)){
                if("866250060552647".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7208063");
                    devDTO.setLat("35.1251990");
                }
                if("866250060560277".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7212526");
                    devDTO.setLat("35.1232193");
                }
                if("866250060599531".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7202398");
                    devDTO.setLat("35.1274594");
                }
                if("866250060601519".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7233125");
                    devDTO.setLat("35.1260695");
                }
                if("866250060585191".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7232374");
                    devDTO.setLat("35.1235709");
                }
                if("866250061178004".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7222310");
                    devDTO.setLat("35.1255781");
                }
                if("866547058633994".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7245816");
                    devDTO.setLat("35.1268165");
                }
                if("D83590999-D2".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7211324");
                    devDTO.setLat("35.1289195");
                }
                if("D83590999-D77".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7234670");
                    devDTO.setLat("35.1255921");
                }
                if("D83590999-D13".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7193986");
                    devDTO.setLat("35.1251428");
                }
            }
            else if("sf".equals(type)){
                if("866250060578113".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8741125");
                    devDTO.setLat("35.0761110");
                }
                if("866250060589003".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8749923");
                    devDTO.setLat("35.0763463");
                }
                if("866250060597584".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8773440");
                    devDTO.setLat("35.0751908");
                }
                if("866250060602723".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8760094");
                    devDTO.setLat("35.0734944");
                }
                if("866250060590894".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8741812");
                    devDTO.setLat("35.0755998");
                }
                if("866250060544214".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8766593");
                    devDTO.setLat("35.0758447");
                }
                if("866250060602723".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8772675");
                    devDTO.setLat("35.0758497");
                }
                if("866250060589003".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8744559");
                    devDTO.setLat("35.075646");
                }
                if("866250060578113".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8758741");
                    devDTO.setLat("35.0759453");
                }
                if("866250060597584".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7402395");
                    devDTO.setLat("35.1573188");
                }
                if("866250060503087".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7398617");
                    devDTO.setLat("35.1556297");
                }
                if("866250061177683".equals(devDTO.getDevId())){
                    devDTO.setLng("107.875137");
                    devDTO.setLat("35.0758431");
                }
                if("866250061176222".equals(devDTO.getDevId())){
                    devDTO.setLng("107.8761183");
                    devDTO.setLat("35.0751071");
                }
            }
            else if("cw".equals(type)){
                if("866250060601519".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9070227");
                    devDTO.setLat("35.0734470");
                }
                if("866250060599531".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9092157");
                    devDTO.setLat("35.0735594");
                }
                if("866250060597931".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9069969");
                    devDTO.setLat("35.0731800");
                }
                if("866250060596255".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9077222");
                    devDTO.setLat("35.0731800");
                }
                if("866250060584855".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9093916");
                    devDTO.setLat("35.0729728");
                }
                if("866250060556655".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9086535");
                    devDTO.setLat("35.0705001");
                }
                if("866250060552647".equals(devDTO.getDevId())){
                    devDTO.setLng("107.9080827");
                    devDTO.setLat("35.0705633");
                }
            }
            else if("rj".equals(type)){
                // 杀虫灯
                if("865328061479555".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74185");
                    devDTO.setLat("35.15686");
                }
                if("865328061480850".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74107");
                    devDTO.setLat("35.15409");
                }
                if("865328061476833".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74457");
                    devDTO.setLat("35.15542");
                }
                if("865328061481106".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74414");
                    devDTO.setLat("35.15302");
                }
                if("865328061442363".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74839");
                    devDTO.setLat("35.15492");
                }
                if("865328061272794".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74719");
                    devDTO.setLat("35.15281");
                }

                // 虫情
                if("866547058636930".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74575");
                    devDTO.setLat("35.15335");
                }

                // 土壤
                if("866250060554569".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7409");
                    devDTO.setLat("35.15736");
                }if("866250060599119".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7410");
                    devDTO.setLat("35.15547");
                }if("866250060590233".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74047");
                    devDTO.setLat("35.15385");
                }if("866250060557455".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74143");
                    devDTO.setLat("35.15271");

                }if("866250060605650".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74266");
                    devDTO.setLat("35.15582");

                }if("866250060557331".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74419");
                    devDTO.setLat("35.15567");
                }
                if("866250060588419".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74382");
                    devDTO.setLat("35.15465");
                }
                if("866250060601576".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74324");
                    devDTO.setLat("35.15325");
                }
                if("866250060503061".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74599");
                    devDTO.setLat("35.15483");
                }
                if("866250060567512".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74537");
                    devDTO.setLat("35.15407");
                }
                if("866250060598376".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74421");
                    devDTO.setLat("35.15248");
                }
                if("866250060590498".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74764");
                    devDTO.setLat("35.15427");
                }
                if("866250060560210".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74732");
                    devDTO.setLat("35.15285");
                }
                if("866250060573536".equals(devDTO.getDevId())){
                    devDTO.setLng("107.74219");
                    devDTO.setLat("35.15474");
                }


                // 气象
                if("866250060601592".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7419406");
                    devDTO.setLat("35.1561373");
                }
                if("866250060597881".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7445936");
                    devDTO.setLat("35.1545441");
                }
                if("866250060599283".equals(devDTO.getDevId())){
                    devDTO.setLng("107.7474249");
                    devDTO.setLat("35.1533482");
                }

//                if("866250060554569".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7466452");
//                    devDTO.setLat("35.1546227");
//                }
//                if("866250060599119".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7475127");
//                    devDTO.setLat("35.1523415");
//                }
//                if("866250060590233".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7459534");
//                    devDTO.setLat("35.1540235");
//                }
//                if("866250060557455".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7458520");
//                    devDTO.setLat("35.1527510");
//                }
//                if("866250060605650".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7463105");
//                    devDTO.setLat("35.1545759");
//                }
//                if("866250060557331".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7433242");
//                    devDTO.setLat("35.1560642");
//                }
//                if("866250060588419".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7425034");
//                    devDTO.setLat("35.1542342");
//                }
//                if("866250060601576".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7430755");
//                    devDTO.setLat("35.1553663");
//                }
//                if("866250060503061".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7411110");
//                    devDTO.setLat("35.1555925");
//                }
//                if("866250060567512".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7412071");
//                    devDTO.setLat("35.1559664");
//                }
//                if("866250060598376".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7414878");
//                    devDTO.setLat("35.1567163");
//                }
//                if("866250060590498".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7416234");
//                    devDTO.setLat("35.1569974");
//                }
//                if("866250060560210".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7417309");
//                    devDTO.setLat("35.1573472");
//                }
//                if("866250060573536".equals(devDTO.getDevId())){
//                    devDTO.setLng("107.7418926");
//                    devDTO.setLat("35.1577995");
//                }
            }





            if(devDTO.getHeartbeatTime() == null){
                offlineNum += 1;
                devDTO.setState("2");
            }else {
                Duration dur = Duration.between(devDTO.getHeartbeatTime(), now);
                if("虫情测报仪".equals(devDTO.getDevType()) || EQU_TYPE_KILL_INSECT.equals(devDTO.getDevType()) || EQU_TYPE_VIDEO.equals(devDTO.getDevType())){
                    if(EQU_TYPE_VIDEO.equals(devDTO.getDevType()) && ("sf".equals(type) || "rj".equals(type))){
                        onlineNum += 1;
                        devDTO.setState("1");
                    }else {
                        if(dur.toMinutes() > 60) {
                            offlineNum += 1;
                            devDTO.setState("2");
                        } else {
                            onlineNum += 1;
                            devDTO.setState("1");
                        }
                    }
                }else {
                    if(dur.toMinutes() > 10) {
                        offlineNum += 1;
                        devDTO.setState("2");
                    } else {
                        onlineNum += 1;
                        devDTO.setState("1");
                    }
                }
//                if (EQU_TYPE_VIDEO.equals(devDTO.getDevType())) {
//                    if (dur.toMinutes() > 60) {
//                        offlineNum += 1;
//                        devDTO.setState("2");
//                    } else {
//                        onlineNum += 1;
//                        devDTO.setState("1");
//                    }
//                }else {
//                    onlineNum += 1;
//                    devDTO.setState("1");
//                }
            }
        }
        Map<String, List<DevDTO>> listMap = allDev.stream().collect(Collectors.groupingBy(DevDTO::getDevType));
        List<JSONObject> jsonList = new ArrayList<>();
        for(String key : listMap.keySet()){
            JSONObject json = new JSONObject();
            json.put("name", key);
            List<DevDTO> list = listMap.get(key);
            int size = list.size();
            json.put("total", list.size());
            long online = list.stream().filter(x -> "1".equals(x.getState())).count();
            json.put("online", online);
            json.put("offline", size - online);
            jsonList.add(json);
        }
        Long videoCnt = 0L;
        Long total = 0L;
        total = onlineNum + offlineNum;
//        if("sf".equals(type) || "rj".equals(type)){
//            videoCnt = allDev.stream().filter(x -> EQU_TYPE_VIDEO.equals(x.getDevType())).count();
//            total = onlineNum + offlineNum + videoCnt;
//            onlineNum = onlineNum + videoCnt;
//        }else {
//            total = onlineNum + offlineNum;
//        }
        object.put("onlineNum", onlineNum);         // 在线数量
        object.put("onlineNumRatio", MathUtils.percentage(onlineNum, total));    // 在线百分比
        object.put("offlineNum", offlineNum);       // 离线数量
        object.put("offlineNumRatio", MathUtils.percentage(offlineNum, total));  // 离线百分比
        object.put("devState", jsonList);  // 每种类型得设备总量和在线数量
        object.put("allDev", allDev);  // 每种类型得设备总量和在线数量
        return success(object);
    }

    // 获取所有设备  传了 devType 则获取指定类型的设备
    @GetMapping(value = "/getAllDev")
    private Object getAllDev(String type, String devType){
        if (StringUtils.isBlank(type))
            type = "cw";
        List<DevDTO> allDev = new ArrayList<>();
        if ("cw".equals(type)) {
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                GetCWDevData.getToken();
                allDev = GetCWDevData.getAllDev();
                GetCWDevData.allDev = allDev;
//            }else
//                allDev = GetCWDevData.allDev;
        } else if ("sf".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevDataSF.allDev)) {
                GetCWDevDataSF.getToken();
                allDev = GetCWDevDataSF.getAllDev();
                allDev.addAll(FruitController.sfVideoList);
                GetCWDevDataSF.allDev = allDev;
//            } else
//                allDev = GetCWDevDataSF.allDev;
        }
        else if ("rj".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevDataRJ.allDev)) {
                GetCWDevDataRJ.getToken();
                allDev = GetCWDevDataRJ.getAllDev();
                allDev.addAll(FruitController.rjVideoList);
                GetCWDevDataRJ.allDev = allDev;
//            }else
//                allDev = GetCWDevDataRJ.allDev;
        }else if ("qfx".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                GetCWDevData.getToken();
                allDev = GetCWDevData.getAllDev().stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
//            }else
//                allDev = GetCWDevData.allDev.stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
        }

        LocalDateTime now = LocalDateTime.now();
        for (DevDTO devDTO : allDev) {
            Duration dur = null;
            try {
                dur = Duration.between(devDTO.getHeartbeatTime(), now);
            }catch (Exception e){
                devDTO.setState("2");
            }
            if(dur == null){
                devDTO.setState("2");
                continue;
            }

            if ("虫情测报仪".equals(devDTO.getDevType()) || EQU_TYPE_KILL_INSECT.equals(devDTO.getDevType()) || EQU_TYPE_VIDEO.equals(devDTO.getDevType())) {
                if (dur.toMinutes() > 60) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            } else {
                if (dur.toMinutes() > 10) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            }
        }

        if(StringUtils.isNotBlank(devType))
            return success(allDev.stream().filter(x -> x.getDevType().equals(devType)).collect(Collectors.toList()));
        else
            return success(allDev);
    }



    // 根据设备类型获取设备列表
    @GetMapping(value = "/getDevListByType")
    private Object getDevListByType(String devType, String type){
        if (StringUtils.isBlank(type))
            type = "cw";
        List<DevDTO> allDev = new ArrayList<>();
        if ("cw".equals(type)) {
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                GetCWDevData.getToken();
                allDev = GetCWDevData.getAllDev();
                GetCWDevData.allDev = allDev;
//            }else
//                allDev = GetCWDevData.allDev;
        } else if ("sf".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevDataSF.allDev)) {
                GetCWDevDataSF.getToken();
                allDev = GetCWDevDataSF.getAllDev();
                allDev.addAll(FruitController.sfVideoList);
                GetCWDevDataSF.allDev = allDev;
//            }else
//                allDev = GetCWDevDataSF.allDev;
        }
        else if ("rj".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevDataRJ.allDev)) {
                GetCWDevDataRJ.getToken();
                allDev = GetCWDevDataRJ.getAllDev();
                allDev.addAll(FruitController.rjVideoList);
                GetCWDevDataRJ.allDev = allDev;
//            }else
//                allDev = GetCWDevDataRJ.allDev;
        }
        else if ("qfx".equals(type)){
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                GetCWDevData.getToken();
                allDev = GetCWDevData.getAllDev().stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
//            }else
//                allDev = GetCWDevData.allDev.stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
        }
        LocalDateTime now = LocalDateTime.now();
        for (DevDTO devDTO : allDev) {
            Duration dur = null;
            try {
                dur = Duration.between(devDTO.getHeartbeatTime(), now);
            }catch (Exception e){
                devDTO.setState("2");
            }
            if(dur == null){
                devDTO.setState("2");
                continue;
            }
            if ("虫情测报仪".equals(devDTO.getDevType()) || EQU_TYPE_KILL_INSECT.equals(devDTO.getDevType()) || EQU_TYPE_VIDEO.equals(devDTO.getDevType())) {
                if (dur.toMinutes() > 60) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            } else {
                if (dur.toMinutes() > 10) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            }
        }
        return success(allDev.stream().filter(x -> x.getDevType().equals(devType)).collect(Collectors.toList()));
    }




    // 获取播放地址
    @GetMapping(value = "/getVideoUrl")
    private Object getVideoUrl(String devId, String type){
        if (StringUtils.isBlank(type))
            type = "cw";
        if("sf".equals(type)){
            GetCWDevDataSF.getToken();
            return success(GetCWDevDataSF.getVideo(devId));
        }
        if("rj".equals(type)){
            GetCWDevDataRJ.getToken();
            return success(GetCWDevDataRJ.getVideo(devId));
        }
        GetCWDevData.getToken();
        return success(GetCWDevData.getVideo(devId));
    }
    // 控制视频旋转
    @GetMapping(value = "/videoMove")
    private Object videoMove(String devId, String val, String type){
        if (StringUtils.isBlank(type))
            type = "cw";
        if("sf".equals(type)){
            GetCWDevDataSF.getToken();
            return success(GetCWDevDataSF.videoMove(devId, val));
        }
        if("rj".equals(type)){
            GetCWDevDataRJ.getToken();
            return success(GetCWDevDataRJ.videoMove(devId, val));
        }
        GetCWDevData.getToken();
        return success(GetCWDevData.videoMove(devId, val));
    }



    @GetMapping(value = "/getNowData")
    public Object getNowData(String devId, String devType, String type){
        // devType 气象监测站  土壤墒情站  虫情测报仪  杀虫灯 摄像机
        if (StringUtils.isBlank(type))
            type = "cw";

        List<DevDTO> allDev = new ArrayList<>();
        if("cw".equals(type)){
            GetCWDevData.getToken();
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                allDev = GetCWDevData.getAllDev();
                GetCWDevData.allDev = allDev;
//            }
        }
        else if("sf".equals(type)){
            GetCWDevDataSF.getToken();
//            if (CollectionUtils.isEmpty(GetCWDevDataSF.allDev)) {
                allDev = GetCWDevDataSF.getAllDev();
                GetCWDevDataSF.allDev = allDev;
//            }
            allDev.addAll(FruitController.sfVideoList);
        }
        else if("rj".equals(type)){
            GetCWDevDataRJ.getToken();
//            if (CollectionUtils.isEmpty(GetCWDevDataRJ.allDev)) {
                allDev = GetCWDevDataRJ.getAllDev();
                GetCWDevDataRJ.allDev = allDev;
//            }
            allDev.addAll(FruitController.rjVideoList);
        }
        else if ("qfx".equals(type)){
            GetCWDevData.getToken();
//            if (CollectionUtils.isEmpty(GetCWDevData.allDev)) {
                allDev = GetCWDevData.getAllDev();
                GetCWDevData.allDev = allDev;
//            }
            allDev = GetCWDevData.allDev.stream().filter(x -> FruitController.idList.contains(x.getDevId())).collect(Collectors.toList());
        }

        LocalDateTime now = LocalDateTime.now();
        for (DevDTO devDTO : allDev) {
            Duration dur = null;
            try {
                dur = Duration.between(devDTO.getHeartbeatTime(), now);
            }catch (Exception e){
                devDTO.setState("2");
            }
            if(dur == null){
                devDTO.setState("2");
                continue;
            }
            if ("虫情测报仪".equals(devDTO.getDevType()) || EQU_TYPE_KILL_INSECT.equals(devDTO.getDevType()) || EQU_TYPE_VIDEO.equals(devDTO.getDevType())) {
                if (dur.toMinutes() > 60) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            } else {
                if (dur.toMinutes() > 10) {
                    devDTO.setState("2");
                } else {
                    devDTO.setState("1");
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        if("气象监测站".equals(devType) || "土壤墒情站".equals(devType) || EQU_TYPE_KILL_INSECT.equals(devType)){

//            if("cw".equals(type))
//                jsonObject.put("data", devData.getNowData(devId));
//            else if("sf".equals(type))
//                jsonObject.put("data", devDataSF.getNowData(devId));
//            else if("rj".equals(type))
//                jsonObject.put("data", GetCWDevDataRJ.getNowData(devId));

            jsonObject.put("data", shiJiRuiTongDao.getLast(devId));
            jsonObject.put("devList", allDev.stream().filter(x -> devType.equals(x.getDevType())).collect(Collectors.toList()));
            return success(jsonObject);
        }else if("虫情测报仪".equals(devType)){
//            List<ShiJiRuiTong> insectHistoryData = new ArrayList<>();
//            if("cw".equals(type)){
//                insectHistoryData = devData.getInsectHistoryData(devId, LocalDate.now().minusDays(1).toString(), LocalDate.now().toString(), GetCWDevData.getInsectHistoryDataUrl)
//                        .stream().sorted(Comparator.comparing(ShiJiRuiTong::getVal).reversed()).limit(10).collect(Collectors.toList());
//            }else if("sf".equals(type)){
//                insectHistoryData = devDataSF.getInsectHistoryData(devId, LocalDate.now().minusDays(1).toString(), LocalDate.now().toString(), GetCWDevData.getInsectHistoryDataUrl)
//                        .stream().sorted(Comparator.comparing(ShiJiRuiTong::getVal).reversed()).limit(10).collect(Collectors.toList());
//            }else if("rj".equals(type)){
//                insectHistoryData = GetCWDevDataRJ.getInsectHistoryData(devId, LocalDate.now().minusDays(1).toString(), LocalDate.now().toString(), GetCWDevData.getInsectHistoryDataUrl)
//                        .stream().sorted(Comparator.comparing(ShiJiRuiTong::getVal).reversed()).limit(10).collect(Collectors.toList());
//            }
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            for (ShiJiRuiTong shiJiRuiTong : insectHistoryData) {
//                String time = LocalDateTime.parse(shiJiRuiTong.getVal().split("\\.")[0].replace("T", " "), formatter).format(formatter);
//                shiJiRuiTong.setVal(time);
//            }

            jsonObject.put("data", shiJiRuiTongDao.getInsectHistoryData(devId));
            jsonObject.put("devList", allDev.stream().filter(x -> devType.equals(x.getDevType())).collect(Collectors.toList()));
            return success(jsonObject);
        }else if(EQU_TYPE_VIDEO.equals(devType)){
            if("cw".equals(type))
                jsonObject.put("data", GetCWDevData.getVideo(devId));
            else if("sf".equals(type))
                jsonObject.put("data", FruitController.sfVideoList.get(0).getUrl());
            else if("rj".equals(type))
                jsonObject.put("data", FruitController.rjVideoList.get(0).getUrl());
            jsonObject.put("devList", allDev.stream().filter(x -> devType.equals(x.getDevType())).collect(Collectors.toList()));
            return success(jsonObject);
        }
        return fail("参数错误");
    }


    // 获取历史数据
    @GetMapping(value = "/getHistoryData")
    public Object getHistoryData(String devId, String devType, String startTime, String endTime){
        if(EQU_TYPE_KILL_INSECT.equals(devType)){
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime))
                return success(shiJiRuiTongDao.getHistoryData(devId, startTime, endTime));
            else
                return success(shiJiRuiTongDao.getHistoryData(devId));
        }
        if("气象监测站".equals(devType) || "土壤墒情站".equals(devType)){
            if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
                return success(shiJiRuiTongDao.getHistoryData(devId, startTime, endTime).stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            }else {
                return success(shiJiRuiTongDao.getHistoryData(devId).stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            }
        }else if("虫情测报仪".equals(devType)){
            if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
                return success(shiJiRuiTongDao.getHistoryData(devId, startTime, endTime));
            }else {
                return success(shiJiRuiTongDao.getHistoryData(devId));
            }
        }
        return fail("参数错误");
    }


    @GetMapping(value = "/getHistoryDevData")
    public Object getHistoryDevData(String devId, String paramName, String startTime, String endTime, String type){
        if(StringUtils.isBlank(type)){
            type = "cw";
        }
        return success(shiJiRuiTongDao.getHistoryData(devId, paramName, startTime, endTime));
    }



    //  devType 1=气象监测站  2=土壤墒情站  5=杀虫灯
    @GetMapping(value = "/analysis")
    public Object Analysis(String devType, String yearMonth, String type){
        if (StringUtils.isBlank(type))
            type = "cw";

        List<JSONObject> analysis = shiJiRuiTongDao.getAnalysis(yearMonth, devType, type);
        for(JSONObject json : analysis){
            String normal = "";
            String paramName = json.getString("paramName");
            if("空气湿度".equals(paramName))
                normal = "20~100%";
            if("光照强度".equals(paramName))
                normal = "0~1000000lux";
            if("大气压".equals(paramName))
                normal = "90~105kpa";
            if("空气温度".equals(paramName))
                normal = "-5~40℃";
            if("风速".equals(paramName))
                normal = "0~17.1m/s";
            if("风向".equals(paramName))
                normal = "0~360°";
            if("总辐射".equals(paramName))
                normal = "0~1000W/m2";
            if("降雨量".equals(paramName))
                normal = "0~100mm/min";

            if("土壤氮".equals(paramName) || "土壤磷".equals(paramName) || "土壤钾".equals(paramName))
                normal = "0~500mg/L";
            if("土壤PH".equals(paramName))
                normal = "0~16";
            if("土壤温度".equals(paramName))
                normal = "0~50℃";
            if("土壤湿度".equals(paramName))
                normal = "0~100%";
            if("土壤盐分".equals(paramName))
                normal = "0~5000mg/l";
            json.put("normal", normal);
        }
        return success(analysis);
    }

    // 图形汇总下面的图表
    @GetMapping(value = "/line")
    public Object line(String paramName, String yearMonth, String type){
        List<JSONObject> lineList = shiJiRuiTongDao.getLine(yearMonth, paramName, type);
        Map<String, List<JSONObject>> cTime = lineList.stream().collect(Collectors.groupingBy(x -> x.getString("cTime")));
        return success(cTime);
    }







    @Autowired
    private FruitUserDao fruitUserDao;
    @Autowired
    private CommonProperties tokenProperties;

    public static final String ROOT = "fruitUpload";
    @Autowired
    private ResourceLoader resourceLoader;


    @GetMapping(value = "/findById")
    public Object findById(String id) {
        return success(fruitUserDao.findById(id).orElseThrow(() -> new BusinessException("该用户不存在")));
    }



    @PostMapping(value = "/login")
    public Object login(String username, String password) {
        FruitUser user = fruitUserDao.findByUsername(username);
        Assert.isFalse(user == null, () -> new BusinessException("账号不存在"));
        Assert.isTrue(user.getPassword().equals(CryptUtil.md5(password)), () -> new BusinessException("密码错误"));
        JSONObject result = new JSONObject();
        result.put("token", TokenUtil.getToken(JSONObject.toJSONString(user), tokenProperties.getSecret(), 60 * 24 * 1000));
        result.put("userInfo", user);
        return success(result);
    }








    @PostMapping(value = "/save")
    public Object update(FruitUser fruitUser, HttpServletRequest request) {
        String exist;
        if(StringUtils.isBlank(fruitUser.getId()))
            exist = fruitUserDao.checkByUsername(fruitUser.getUsername());
        else
            exist = fruitUserDao.checkByUsername(fruitUser.getUsername(), fruitUser.getId());
        Assert.isFalse(StringUtils.isNotBlank(fruitUser.getUsername()) && StringUtils.isNotBlank(exist), () -> new BusinessException("username已存在"));
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        if(file != null)
            fruitUser.setHeadImg(upload(file));
        if(StringUtils.isNotBlank(fruitUser.getPassword()))
            fruitUser.setPassword(CryptUtil.md5(fruitUser.getPassword()));
        return success(fruitUserDao.save(fruitUser));
    }


    @RequestMapping(value = "/show/{filename:.+}")
    public void loadFile(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ErrorPageException {
        BufferedInputStream in = null;
        ByteArrayOutputStream bos = null;
        String ys = request.getParameter("ys");
        try {
            File file = resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()).getFile();
            bos = new ByteArrayOutputStream();
            String suf = FileUtil.getSuffix(filename).toLowerCase();
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            if (suf.contains("png") || suf.contains("jpg") || suf.contains("gif") || suf.contains("JPEG")) {
                response.setContentType("image/png");
            } else {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            }
            response.getOutputStream().write(bos.toByteArray());
        } catch (IOException e) {
            throw new ErrorPageException("文件【" + filename + "】不存在");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String upload(MultipartFile file) {
        File destFile = new File(Paths.get(ROOT).toAbsolutePath().toString());
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
        String filename = System.currentTimeMillis() + "_" + RandomUtil.random(6) + type;// 取当前时间戳作为文件名
        File sourceFile = new File(Paths.get(ROOT, filename).toAbsolutePath().toString());
        try {
            file.transferTo(sourceFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("保存文件失败");
        }
        return filename;
    }



}
